import com.alibaba.fastjson.JSONObject;

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;

public class TcpServer {
    public static void main(String[] args) throws IOException {
        ServerSocket serverSocket = new ServerSocket(5000);
        Socket accept = serverSocket.accept();
        InputStream inputStream = accept.getInputStream();
        OutputStream outputStream = accept.getOutputStream();

        // 第一次读取4byte,读取加密还是解密
        int choose = ByteToInt.toInt(getBytes(inputStream, 4));

        byte[] lenBytes = getBytes(inputStream, 4);
        int jsonLen = ByteToInt.toInt(lenBytes);

        byte[] jsonBytes = getBytes(inputStream, jsonLen);
        FileInfo fileInfo = JSONObject.parseObject(jsonBytes,FileInfo.class);

        byte[] buf = new byte[1024];
        long fileLeft = fileInfo.getLength();
//        File file = new File("/Users/edz/banyuan/Java/20.Socket/practice/02.tcp","Refine"+fileInfo.getName());
//        BufferedOutputStream bufferedOutputStream = new BufferedOutputStream(new FileOutputStream(file));

        int read = inputStream.read(buf, 0, (int) Math.min(fileLeft, buf.length));
        while (fileLeft>0){
            if (choose == 1) {
                for (int i = 0; i < read; i++) {
                    buf[i] = (byte) Encode.caesarEncode((char) buf[i]);
                }
            }else {
                for (int i = 0; i < read; i++) {
                    buf[i] = (byte) Decode.caesarDecode((char) buf[i]);
                }
            }
            outputStream.write(buf,0,read);
            fileLeft-=read;
            read = inputStream.read(buf,0,(int) Math.min(fileLeft, buf.length));
        }
        System.out.println("解密或者加密成功！");
        accept.close();

    }


    private static byte[] getBytes(InputStream inputStream, int total) throws IOException {
        byte[] lengthBytes = new byte[total];
        int len = inputStream.read(lengthBytes);
        if (len != lengthBytes.length) {
            throw new IllegalArgumentException("读取长度错误");
        }
        return lengthBytes;
    }
}
